package com.lris.handle;

import com.alibaba.fastjson2.JSON;
import com.lris.enumerates.CommandType;
import com.lris.pojodata.Command;
import com.lris.rest.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;



public class WebsocketHandle extends SimpleChannelInboundHandler<TextWebSocketFrame>  {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        //格式化成json
        try {
            Command command = JSON.parseObject(frame.text(), Command.class);
            switch (CommandType.math(command.getCode())){
                case CONNECTION ->ConnectionHandle.execute(ctx,command);
                case CHAT -> ChatHandle.execute(ctx,frame);
                case JOIN -> JoinHandle.execute(ctx);
                case ADD -> UserHandle.execute(ctx,frame);
                default -> ctx.channel().writeAndFlush(Result.fail("不支持的code类型"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
            throw new RuntimeException(e.getMessage());
        }
    }
}
